import {Component, ViewChild} from '@angular/core';
import {
    AlertController, IonicFormInput, IonicPage, NavController, NavParams, ToastController, Platform,
    LoadingController, ItemSliding, Content,Events
} from 'ionic-angular';
import {FileTransfer} from '@ionic-native/file-transfer';
import { Network } from '@ionic-native/network';
import * as moment from "moment";

import {ScheduleItem} from "../../../../model/pages/schedule/schedule-add/schedule-add.model";
import {ClientNoteEditProvider} from "../../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {FileService} from "../../../../services/native/file/file.service";
import {RecorderService} from "../../../../services/recorder.service";
import {LocalStorageService} from "../../../../services/native/local-storage/local-storage.service";
import {ScheduleAddProvider} from "../../../../providers/schedule/schedule-add/schedule-add.provider";
import {LoadingService} from "../../../../services/common/loading.service";
import {MessageBushService} from "../../../../services/common/message-bush.service";
import {ToastService} from '../../../../services/common/toast.service';

/**
 * 编辑客户笔记
 */
@IonicPage()
@Component({
    selector: 'page-client-note-edit',
    templateUrl: 'client-note-edit.html',
    providers: [
        ClientNoteEditProvider,
        ScheduleAddProvider,
        LocalStorageService,
        FileService,
        FileTransfer,
        LoadingService,
        ToastService,
        Network
    ]
})
export class ClientNoteEditPage {
    @ViewChild(Content) content: Content;
    // 文本笔记
    @ViewChild('noteText') noteText: IonicFormInput;
    // 操作类型 1为新增，2为修改
    private opType: number;
    // 笔记
    private clientNoteModel: any = {};
    // 笔记类型
    private noteType: number;
    // 确认弹框
    private alertObj: any;
    // 上一条文字笔记
    private prevNote: string = '';
    // 是否可以二次编辑
    public editStatus: boolean = true;

    // 视口中心区域高度
    private viewCenterHeight: number;
    // textarea高度
    private texareaHeight: number = 800;
    // texarea以上区域高度
    private itemsHeight: number;

    // 录音组件是否加载
    private audioStatus: boolean = true;
    // 录音按钮
    private audioBtn: number = 2;
    // 语音时长
    private voiceLength: number = 0;
    // 语音文件
    private voiceFile: any = '';
    // 播放语音ID
    private id: string = '123';
    // 是否是新建的语音标记
    private isNewVoice: boolean = false;
    // 笔记初始类型
    initNoteType:number;
    // 是否关联到日程
    private addSchedule: boolean;
    // 日程结束
    private endRepeat: any = '永不';//结束重复时间:永不 or UNIX时间戳
    // 日程事项
    private data: ScheduleItem = new ScheduleItem();
    // 确定离开页面
    private leavePage:boolean=true;
    // 网络状态
    private networkStatus:boolean;

    /**
     * 构造函数
     * @param {NavController} navCtrl
     * @param {NavParams} navParams
     * @param {ToastController} toastCtrl
     * @param {ClientNoteEditProvider} clientNoteAddProvider
     */
    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public platform: Platform,
                public toastCtrl: ToastController,
                public alertCtrl: AlertController,
                public loadCtr: LoadingController,
                public fileService: FileService,
                public recorderService: RecorderService,
                public scheduleAddProvider: ScheduleAddProvider,
                public clientNoteAddProvider: ClientNoteEditProvider,
                public loadingService: LoadingService,
                public toastService: ToastService,
                public event:Events,
                public network:Network
                ) {
    }

    public backButtonHandle = () => this.backClickHandle();

    /**
     * 视图加载事件
     */
    ionViewDidLoad() {
        console.log(this.navParams.get('params'));
        if (this.navParams.get('params')) {
            this.clientNoteModel = JSON.parse(JSON.stringify(this.navParams.get('params')));
            this.voiceFile = this.clientNoteModel.voiceUrl;
            this.voiceLength = this.clientNoteModel.voiceLength;
            this.voiceFile ? this.isNewVoice = false : null;
        }

        this.navParams.get('opType')?this.opType = this.navParams.get('opType'):null;
        this.navParams.get('id')?this.clientNoteModel.clientNumber=this.navParams.get('id'):null;

        this.initNoteType=this.clientNoteModel.noteType;
        this.opType !=2 && this.clientNoteModel.contentType == 2 ? this.isNewVoice = true : null;
        this.clientNoteModel.noteType ? this.noteType = this.clientNoteModel.noteType : 4;
        this.clientNoteModel.content ? this.prevNote = this.clientNoteModel.content : null;
        this.clientNoteModel.clientType=this.navParams.get('base').clientType;
        setTimeout(() => {
            this.viewCenterHeight = this.content._fixedContent.nativeElement.clientHeight;
            this.itemsHeight = 0;
        }, 200);

        // 测试网络监听
        this.network.onDisconnect().subscribe(()=>{
            this.networkStatus=false;
        });
        this.network.onConnect().subscribe(()=>{
            setTimeout(()=>{
                this.networkStatus=true;
            },3000)
        })
    }

    ionViewWillLeave() {
    }

    // 页面返回
    backClickHandle() {
        this.voiceFile='';
        this.leavePage=false;
        this.navCtrl && this.navCtrl.pop(null, null);
    }

    // 编辑文字笔记
    editFontNote($event, flag) {
        if ($event.data && $event.data.match(/(\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]|\ud83d[\ude80-\udeff])/g)) {
            this.clientNoteModel.content = this.clientNoteModel.content.substr(0, this.clientNoteModel.content.length - 1);
        }
        setTimeout(() => {
            if (this.prevNote.length >= 200 && this.clientNoteModel.content.length >= 200) {
                this.clientNoteModel.content = this.prevNote.substr(0, 200);
                flag ? this.toastService.showToast('最多只能输入200个字') : null;
            } else {
                this.clientNoteModel.content = this.clientNoteModel.content.substr(0, 200);
                this.prevNote = JSON.parse(JSON.stringify(this.clientNoteModel.content));
            }
        }, 100)
    }

    // 备注聚焦调整光标到尾部
    remarkCursor(e) {
        let $this = this;
        if(this.platform.is('ios')){
            let val=this.clientNoteModel.content;
            this.clientNoteModel.content=' ';
            setTimeout(()=>{
                this.clientNoteModel.content=val;
                e.target.click();
            },50);
        }
        window.addEventListener('native.keyboardshow', function (e) {
            //e.keyboardHeight 表示软件盘显示的时候的高度
            $this.texareaHeight = $this.viewCenterHeight - e['keyboardHeight'] - ($this.itemsHeight - e['keyboardHeight']) - window['innerWidth'] / 100 * 110;
        });
    }


    // 录音成功
    recordSuccess($event) {
        this.voiceFile = $event.voiceUrl;
        this.voiceLength = $event.voiceLength;
        this.clientNoteModel.voiceUrl = $event.voiceUrl;
        this.clientNoteModel.voiceLength = $event.voiceLength;
        this.isNewVoice = true;
    }

    // 删除语音
    deleteVoice(e, itemSliding: ItemSliding) {
        e.stopPropagation();
        e.preventDefault();
        this.showConfirm('确定删除？', () => {
            this.clientNoteModel.voiceUrl = '';
            this.clientNoteModel.voiceLength = 0;
        }, () => {
            itemSliding.close();
        })
    }

    // 选择笔记类型
    selectType(num) {
        this.noteType = num;
        this.clientNoteModel.noteType = num;
    }

    // 日程数据传递
    scheduleTigger($event) {
        this.data = $event;
    }

    // 重复日程结束状态
    setEndRepeat(endRepeat: string) {
        this.endRepeat = endRepeat;
    }

    /**
     * 显示结束重复的时间
     * @param endRepeat '永不'或者时间戳
     * @returns {string}
     */
    getEndRepeatTime(endRepeat) {
        if (endRepeat === '永不') {
            return '永不'
        } else {
            return moment(endRepeat * 1000).format('YYYY年MM月DD日')
        }
    }

    /**
     * 保存
     */
    save() {
        if (!this.clientNoteModel.content && this.clientNoteModel.contentType == 1) {
            this.toastService.showToast('请输入跟进情况');
            return false;
        }
        if (this.addSchedule && !this.data.name) {
            this.toastService.showToast('请输入日程标题');
            return false;
        }
        if (this.clientNoteModel.contentType == 2 && !this.clientNoteModel.voiceUrl) {
            this.toastService.showToast('请录入语音');
            return false;
        }
        if (this.data.endTime < this.data.startTime) {
            this.toastService.showToast('时间范围输入有误');
            return false;
        }
        if (this.clientNoteModel.contentType == 2 && !this.clientNoteModel.voiceUrl && this.opType == 2) {
            this.toastService.showToast('编辑语音不能为空');
            return false;
        }
        /*if (this.clientNoteModel.contentType == 2 && this.clientNoteModel.voiceUrl && this.opType == 2 && !this.isNewVoice && !this.addSchedule&&this.initNoteType==this.clientNoteModel.noteType) {
            this.toastService.showToast('语音未编辑');
            return false;
        }*/
        if (this.clientNoteModel.contentType == 2 && this.isNewVoice) {
            this.loadingService.showLoading();
            this.voiceUpload();
        } else {
            this.loadingService.showLoading();
            this.saveNote();
        }
    }

    // 到云端删除语音
    deleteVoiceSource() {
        this.fileService.deleteFile(this.clientNoteModel.voiceUrl).subscribe((res) => {

        })
    }

    // 语音文件上传
    voiceUpload() {
        this.voiceFile='';
        this.fileService.saveFile(this.recorderService.getFilePath(this.clientNoteModel.voiceUrl),
            this.clientNoteModel.voiceUrl,
            this.recorderService.getMimeType()).subscribe(result => {
            this.clientNoteModel.voiceUrl = result;
            this.saveNote();
        }, err => {
            this.voiceFile=this.data.voiceUrl;
            this.loadingService.dismissLoading();
            if(this.networkStatus){
                this.toastService.showToast('语音上传失败');
            }else{
                this.event.publish('checkNet');
                //this.toastService.showToast('当前网络环境异常，请稍后重试');
            }
        });
    }

    /**
     * 保存笔记
     */
    saveNote() {
        if (this.opType != 2) {
            this.clientNoteAddProvider.saveNote(this.clientNoteModel).subscribe(() => {
                MessageBushService.setMessage(MessageBushService.keys.clientDetailDataUpdated, "1");
                this.cleanScheduleData();
                this.event.publish('progress create');
            }, error => {
                this.loadingService.dismissLoading();
                if (error.status == 500) {
                    this.toastService.showToast("保存失败");
                }
            });
        } else {
            this.clientNoteAddProvider.editNote(this.clientNoteModel.id, this.clientNoteModel).subscribe(() => {
                MessageBushService.setMessage(MessageBushService.keys.clientDetailDataUpdated, "1");
                this.cleanScheduleData();
                this.event.publish('progress update');
            }, error => {
                this.loadingService.dismissLoading();
                if (error.status == 500) {
                    this.toastService.showToast("保存失败");
                }
            });
        }
    }

    // 整理日程数据
    cleanScheduleData() {
        if (this.addSchedule) {
            if (this.endRepeat === '永不') {
                this.data.until = null
            } else {
                //结束重复时分取日程结束时间的时分
                let hours = moment(new Date(this.data.endTime)).hour();
                let minute = moment(new Date(this.data.endTime)).minute();
                //结束重复年月日结束重复自己的年月日
                let year = moment(new Date(this.endRepeat * 1000)).year();
                let month = moment(new Date(this.endRepeat * 1000)).month();
                let date = moment(new Date(this.endRepeat * 1000)).date();
                this.data.until = moment([year, month, date, hours, minute]).unix();
            }

            this.data.type = 1;
            this.data.startTime = this.data.startTime / 1000;
            this.data.endTime = this.data.endTime / 1000;
            if (this.clientNoteModel.contentType == 1) {
                this.data.remark = this.clientNoteModel.content;
                this.data.voiceUrl = '';
                this.data.voiceLength = 0;
            } else {
                this.data.remark = '';
                this.data.voiceUrl = this.clientNoteModel.voiceUrl;
                this.data.voiceLength = this.clientNoteModel.voiceLength;
            }
            this.addNewSchedule();
        } else {
            this.loadingService.dismissLoading();
            this.voiceFile='';
            this.leavePage=false;
            this.navCtrl.pop();
        }
    }

    // 添加关联日程
    addNewSchedule() {
        this.voiceFile='';
        this.scheduleAddProvider.postNewScheduleItem(this.data).subscribe((res) => {
            if (res) {
                this.loadingService.dismissLoading();
                this.leavePage=false;
                this.navCtrl.pop();
            }
        }, err => {
            this.voiceFile=this.data.voiceUrl;
            this.loadingService.dismissLoading();
        });
    }

    /**
     * 删除
     */
    delete() {
        this.voiceFile='';
        this.showConfirm('确定删除？', () => {
            this.clientNoteAddProvider.deleteNote(this.clientNoteModel.id).subscribe(() => {
                MessageBushService.setMessage(MessageBushService.keys.clientDetailDataUpdated, "1");
                this.event.publish('progress del');
                this.leavePage=false;
                this.navCtrl.pop();
            }, error => {
                this.voiceFile=this.data.voiceUrl;
                if (error.status == 500) {
                    this.toastService.showToast("删除失败");
                }
            });
        }, () => {
        });
    }


    /**
     * 确认框
     *
     * @private
     * @param {any} msg 询问的消息
     * @param {any} okCallback 用户点击确定后的回调
     * @param {any} cancelCallback 用户点击取消后的回调
     * @memberof ScheduleAddPage
     */
    showConfirm(msg, okCallback, cancelCallback) {
        if (this.alertObj) return;
        this.alertObj = this.alertCtrl.create({
            enableBackdropDismiss: false,
            message: msg,
            buttons: [{
                text: '取消',
                handler: cancelCallback
            }, {
                text: '确定',
                handler: okCallback
            }]
        });
        this.alertObj.onDidDismiss(() => this.alertObj = null);
        this.alertObj.present();
    }
}
